package com.nb.service.impl;

import com.nb.exception.BaseException;
import com.nb.mapper.DoctorMapper;
import com.nb.service.DoctorService;
import com.nb.utils.CurrentHolderUtil;
import com.nb.utils.FileUploadUtil;
import com.nb.utils.UrlUtil;
import com.nb.vo.DoctorVO.*;
import com.nb.vo.DoctorVO.DoctorBodyOV.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class DoctorServicrImpl implements DoctorService {

    @Autowired
    private DoctorMapper doctorMapper;

    @Autowired
    private FileUploadUtil fileUploadUtil;

    @Override
    public DoctorGetInfoVO getDoctorById() {
        DoctorGetInfoVO doctor = doctorMapper.getDoctorById(CurrentHolderUtil.getCurrentId());
        
        // 处理医生头像URL
        if (doctor != null && doctor.getAvatar() != null) {
            doctor.setAvatar(UrlUtil.buildFullUrl(doctor.getAvatar()));
        }
        
        return doctor;
    }

    @Override
    public boolean updateDoctorById(DoctorModifyInfoVO vo) {

        Integer currentId = CurrentHolderUtil.getCurrentId();
        vo.setId(currentId);
        String departmentId = doctorMapper.findDepartmentIdByDepartmentName(vo.getDepartment());
        if (departmentId != null) {
            vo.setDepartmentId(Integer.valueOf(departmentId));

            return doctorMapper.updateDoctorById(vo) > 0;
        } else return false;

    }

    @Override
    public boolean DoctorPublishSource(DoctorPublishSourceBodyOV body) {

        Integer userId = Integer.valueOf(CurrentHolderUtil.getCurrentId());
        String doctorId = doctorMapper.findDoctorIdByUserId(userId);
        String fee =  doctorMapper.getCopayFeeByDoctorId(Integer.valueOf(doctorId));
        body.setDoctorId(Integer.valueOf(doctorId));
        body.setPrice(fee);

        return doctorMapper.doctorPublishSource(body) > 0;
    }

    @Override
    public List<DoctorGetPatientList> doctorGetPatientListById() {

        Integer userId = CurrentHolderUtil.getCurrentId();
        String  doctorId = doctorMapper.findDoctorIdByUserId(userId);

        List<DoctorGetPatientList> doctorGetPatientLists = doctorMapper.getPatientByDoctorId(Integer.valueOf(doctorId));

        return doctorGetPatientLists;
    }

    @Override
    public List<DoctorGetConductedPatientList> doctorGetConductedPatientList() {

        Integer userId = CurrentHolderUtil.getCurrentId();
        String  doctorId = doctorMapper.findDoctorIdByUserId(userId);

        List<DoctorGetConductedPatientList> ConductedPatientList = doctorMapper.getConductedPatientByDoctorId(Integer.valueOf(doctorId));

        return ConductedPatientList;
    }

    @Override
    public List<DoctorGetOrderList> doctorGetOrderList() {

        Integer userId = CurrentHolderUtil.getCurrentId();
        String  doctorId = doctorMapper.findDoctorIdByUserId(userId);

        List<DoctorGetOrderList> doctorGetOrderList = doctorMapper.getOrderList(Integer.valueOf(doctorId));

        return doctorGetOrderList;
    }

    @Override
    public boolean doctorSubmitDiagnosis(DoctorSubmitDiagnosis body) {

        Integer userId = CurrentHolderUtil.getCurrentId();
        String  doctorId = doctorMapper.findDoctorIdByUserId(userId);
        body.setDoctorId(doctorId);

        return doctorMapper.doctorSubmitDiagnosis(body) > 0;
    }

    @Override
    public boolean doctorSubmitPrescription(DoctorSubmitPrescription body) {

        Integer userId = CurrentHolderUtil.getCurrentId();
        String  doctorId = doctorMapper.findDoctorIdByUserId(userId);
        body.setDoctorId(doctorId);

        return doctorMapper.updateMedicalAdviceByMAId(body) > 0;
    }

    @Override
    public boolean doctorMakePrescription(DoctorMakePrescription body) {

        Integer userId = CurrentHolderUtil.getCurrentId();
        String  doctorId = doctorMapper.findDoctorIdByUserId(userId);
        body.setDoctorId(doctorId);

        return doctorMapper.updatePrescriptionByMRId(body) > 0;
    }

    @Override
    public boolean doctorCheckApply(DoctorCheckApply body) {

        Integer userId = CurrentHolderUtil.getCurrentId();
        String  doctorId = doctorMapper.findDoctorIdByUserId(userId);
        body.setDoctorId(doctorId);

        String medicalRecordId = doctorMapper.getMedicalRecordIdByDoctorIdAndPatientId2(body);
        body.setMedicalRecordId(medicalRecordId);

        return doctorMapper.updateExaminationApplicationByMRId(body) > 0;
    }

    @Override
    public boolean doctorCompleteConduct(DoctorCompleteConduct body) {

        Integer userId = CurrentHolderUtil.getCurrentId();
        String  doctorId = doctorMapper.findDoctorIdByUserId(userId);
        body.setDoctorId(doctorId);

        String OrderId = doctorMapper.getRegistrationOrderIdByMedicalRecordId(body);
        body.setOrderId(OrderId);

        return doctorMapper.updateRegistrationOrderMedicalStatusByMRId(body) > 0;
    }

    @Override
    public List<DoctorGetMedicalAdviceList> doctorGetPrescriptionListById() {
        Integer userId = CurrentHolderUtil.getCurrentId();
        String  doctorId = doctorMapper.findDoctorIdByUserId(userId);

        List<DoctorGetMedicalAdviceList> medicalAdviceList = doctorMapper.getMedicalAdviceList(Integer.valueOf(doctorId));

        return medicalAdviceList;
    }

    @Override
    public boolean doctorModifyModifyMedicalAdvice(DoctorModifyMedicalAdvice body) {
        Integer userId = CurrentHolderUtil.getCurrentId();
        String  doctorId = doctorMapper.findDoctorIdByUserId(userId);

        return doctorMapper.modifyPrescription(body) > 0;
    }

    @Override
    public DoctorGetConductForm doctorGetConductFormById(String id) {
        Integer userId = CurrentHolderUtil.getCurrentId();
        String  doctorId = doctorMapper.findDoctorIdByUserId(userId);

        DoctorGetConductFormBody body = new DoctorGetConductFormBody(id,doctorId);

        DoctorGetConductForm forms = doctorMapper.doctorGetConductForm(body);

        return forms;
    }

    @Override
    public List<DoctorGetSourceList> doctorGetSourceListById() {
        Integer userId = CurrentHolderUtil.getCurrentId();
        String  doctorId = doctorMapper.findDoctorIdByUserId(userId);

        List<DoctorGetSourceList> sourceList = doctorMapper.getSourceList(Integer.valueOf(doctorId));

        return sourceList;
    }

    @Transactional // 添加事务管理
    @Override
    public String changeAvatar(MultipartFile file) {
        // 1. 获取当前登录用户ID
        Integer userId = CurrentHolderUtil.getCurrentId();
        if (userId == null) {
            throw new BaseException("无法获取当前用户信息，请重新登录");
        }

        // 2. 使用 FileUploadUtil 保存图片
        // 使用 userId 作为文件名的一部分，增加可读性
        String relativePath = fileUploadUtil.saveImage(file, userId);

        // 3. 更新数据库中的头像路径
        int updatedRows = doctorMapper.updateUserAvatar(userId, relativePath);
        if (updatedRows == 0) {
            // 可以选择抛出异常或记录日志，取决于业务需求
            log.warn("更新用户 {} 的头像失败，可能用户不存在", userId);
            // 如果需要严格保证更新成功，可以抛出异常
            // throw new BaseException("更新头像失败");
        } else {
            log.info("用户 {} 的头像更新成功，新路径: {}", userId, relativePath);
        }

        // 4. 返回新的头像访问路径（完整URL）
        return UrlUtil.buildFullUrl(relativePath); // 确保返回完整 URL
    }

}

